package com.ehotting.mqbd.core.logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ehotting.eaf.core.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class MQSendLogger {


    private Logger logger;



    public MQSendLogger(String loggerName){
        logger = LoggerFactory.getLogger(loggerName);
    }

    public  void info(){
        Map<String,Object> map = new HashMap<String,Object>();
        map.put(LOGGER_KEY.SERIAL, MDC.get(LOGGER_KEY.SERIAL));
        map.put(LOGGER_KEY.FUNCTION, MDC.get(LOGGER_KEY.FUNCTION));
        String timeString = MDC.get(LOGGER_KEY.START_TIME);

        if(timeString!=null){
            Long startTime = Long.parseLong(timeString);
            map.put(LOGGER_KEY.START_TIME, DateUtils.dateToString(new Date(startTime),"yyyy-MM-dd HH:mm:ss"));
            map.put(LOGGER_KEY.COST_TIME,String.valueOf(System.currentTimeMillis() - startTime));
        }

        String request = MDC.get(LOGGER_KEY.REQUEST);
        if(StringUtils.hasText(request)){
            JSONObject requestMap =  JSON.parseObject(request, JSONObject.class);
            map.put(LOGGER_KEY.REQUEST, requestMap);
        }

        String response = MDC.get(LOGGER_KEY.RESPONSE);
        if(StringUtils.hasText(response)){
            JSONObject responseMap =  JSON.parseObject(response, JSONObject.class);
            map.put(LOGGER_KEY.RESPONSE, responseMap);
        }
        String exception = MDC.get(LOGGER_KEY.EXCEPTION);
        if(StringUtils.hasText(exception)){
            map.put(LOGGER_KEY.EXCEPTION, exception);
        }

        logger.info(JSONObject.toJSONString(map));
        LOGGER_KEY.clear();
    }



    public  void info(String s,Object... args){
        logger.info(s,args);
    }
}
